package com.phkj.qdh.ui.fragment.instructionsheet

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.QuickAdapterHelper
import com.chad.library.adapter4.loadState.LoadState
import com.chad.library.adapter4.loadState.trailing.TrailingLoadStateAdapter
import com.flyco.tablayout.listener.OnTabSelectListener
import com.hjq.toast.ToastUtils
import com.phkj.qdh.R
import com.phkj.qdh.bean.InstructionBean
import com.phkj.qdh.bean.MyTab
import com.phkj.qdh.bean.PageInfo
import com.phkj.qdh.databinding.FragmentInstructionSheetBinding
import com.phkj.qdh.ui.adapter.InstructionSheetAdapter
import com.phkj.qdh.utils.MyItemDecoration
import com.phkj.qdh.utils.PAGE_SIZE
import com.phkj.qdh.utils.launchAndRepeatWithViewLifecycle
import kotlinx.coroutines.flow.collectLatest
import java.util.HashMap

/**
 * 指令单首页
 */
class InstructionSheetFragment : Fragment() {

    private var _binding: FragmentInstructionSheetBinding? = null
    private val binding get() = _binding!!
    private val instructionSheetAdapter by lazy { InstructionSheetAdapter() }
    private val instructionSheetAdapterNo by lazy { InstructionSheetAdapter() }
    private lateinit var vm: InstructionVM
    private val pageInfo = PageInfo()
    private val pageInfoNo = PageInfo()
    private lateinit var okHelper: QuickAdapterHelper
    private lateinit var noHelper: QuickAdapterHelper
    private var pos = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentInstructionSheetBinding.inflate(inflater, container, false)
        vm = ViewModelProvider(this, getInstructionVMProvider())[InstructionVM::class.java]
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        okHelper = QuickAdapterHelper.Builder(instructionSheetAdapter)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onFailRetry() {
                    getInstructionList()
                }

                override fun onLoad() {
                    pageInfo.nextPage()
                    getInstructionList()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlInstructionSheet.isRefreshing
                }

            }).build()


        noHelper = QuickAdapterHelper.Builder(instructionSheetAdapterNo)
            .setTrailingLoadStateAdapter(object : TrailingLoadStateAdapter.OnTrailingListener {
                override fun onFailRetry() {
                    getInstructionListNo()
                }

                override fun onLoad() {
                    pageInfoNo.nextPage()
                    getInstructionListNo()
                }

                override fun isAllowLoading(): Boolean {
                    return !binding.srlInstructionSheet.isRefreshing
                }

            }).build()

        binding.run {
            rvInstructionSheet.run {
                layoutManager = LinearLayoutManager(requireContext())
                addItemDecoration(MyItemDecoration(width = 24))
            }
            srlInstructionSheet.setOnRefreshListener {
                if (pos == 0) {
                    refershNo()
                } else {
                    refersh()
                }
            }
            ctl.run {
                setTabData(arrayListOf(MyTab("待处理"), MyTab("已处理")))
                ctl.setOnTabSelectListener(object : OnTabSelectListener {
                    override fun onTabSelect(position: Int) {
                        if (position == 0) {
                            binding.rvInstructionSheet.adapter = noHelper.adapter
                            pos = 0
                            refershNo()
                        } else {
                            binding.rvInstructionSheet.adapter = okHelper.adapter
                            refersh()
                            pos = 1
                        }
                    }

                    override fun onTabReselect(position: Int) {

                    }
                })
            }
        }

        binding.ctl.currentTab = 0

        launchAndRepeatWithViewLifecycle {
            vm.state.collectLatest {
                binding.srlInstructionSheet.isRefreshing = false
            }
        }

        launchAndRepeatWithViewLifecycle {
            vm.instructionListNo.collectLatest {
                if (pageInfoNo.isFirstPage) {
                    instructionSheetAdapterNo.submitList(it)
                } else {
                    instructionSheetAdapterNo.addAll(it)
                }
                binding.srlInstructionSheet.isRefreshing = false
                if (it.size != PAGE_SIZE) {/*

                    Set the status to not loaded, and there is no paging data.
                    设置状态为未加载，并且没有分页数据了
                     */
                    noHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {/*
                    Set the state to not loaded, and there is also paginated data
                    设置状态为未加载，并且还有分页数据
                     */
                    noHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }


        launchAndRepeatWithViewLifecycle {
            vm.instructionList.collectLatest {
                if (pageInfoNo.isFirstPage) {
                    instructionSheetAdapter.submitList(it)
                } else {
                    instructionSheetAdapter.addAll(it)
                }
                binding.srlInstructionSheet.isRefreshing = false
                if (it.size != PAGE_SIZE) {/*

                    Set the status to not loaded, and there is no paging data.
                    设置状态为未加载，并且没有分页数据了
                     */
                    okHelper.trailingLoadState = LoadState.NotLoading(true)
                } else {/*
                    Set the state to not loaded, and there is also paginated data
                    设置状态为未加载，并且还有分页数据
                     */
                    okHelper.trailingLoadState = LoadState.NotLoading(false)
                }
            }
        }

        instructionSheetAdapterNo.setOnItemClickListener { adapter, _, pos ->
            val data = adapter.items.get(pos)
            data?.let { a ->
                parentFragmentManager.commit {
                    addToBackStack("detail")
                    replace(id, InstructionSheetDetailFragment.newInstance(a, ""))
                    setReorderingAllowed(true)
                }
            }

        }

        instructionSheetAdapter.setOnItemClickListener { adapter, _, pos ->
            val data = adapter.items.get(pos)
            data?.let { a ->
                parentFragmentManager.commit {
                    addToBackStack("detail")
                    replace(id, InstructionSheetDetailFragment.newInstance(a, ""))
                    setReorderingAllowed(true)
                }
            }

        }
    }

    override fun onResume() {
        super.onResume()
        if (pos == 0) {
            binding.rvInstructionSheet.adapter = noHelper.adapter
            getInstructionListNo()
        } else {
            binding.rvInstructionSheet.adapter = okHelper.adapter
            getInstructionList()
        }
    }

    fun getInstructionList() {
        val map = HashMap<String, Any?>()
        map["page"] = pageInfo.page
        map["size"] = PAGE_SIZE
        map["deal"] = 1
        vm.getInstructionList(map)
    }

    private fun refersh() {
        pageInfo.reset()
        okHelper.leadingLoadState = LoadState.None
        getInstructionList()
    }


    private fun getInstructionListNo() {
        val map = HashMap<String, Any?>()
        map["page"] = pageInfo.page
        map["size"] = PAGE_SIZE
        map["deal"] = 0
        vm.getInstructionListNo(map)
    }

    private fun refershNo() {
        pageInfo.reset()
        noHelper.leadingLoadState = LoadState.None
        getInstructionListNo()
    }


    companion object {
        @JvmStatic
        fun newInstance() = InstructionSheetFragment().apply {
            arguments = Bundle().apply {
//                    putString(ARG_PARAM1, param1)
//                    putString(ARG_PARAM2, param2)
            }
        }
    }
}